package com.ggh.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/** 

 * 文件上传包括的单文件上传和多文件上传工具类

 * @author 作者 Your-Name: 王秀田

 * @version 创建时间：2019年9月9日 上午11:17:35
 
 * 类说明  

 */
public class UploadFileTool {

	public static String uploadFile(HttpServletRequest request, MultipartFile file)
			throws IllegalStateException, IOException {
		try {
			Thread.sleep(1000);//睡眠1秒
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		}
		// 图片显示地址
				String saveUrl = "";
		        String address="";
				// 如果文件不为空，写入上传路径
					String url = null;
					if (!file.isEmpty()) {
                        String url0 = "D://";
                        url = url0 + "upload/";
						// 定义允许上传的文件扩展名
						HashMap<String, String> extMap = new HashMap<String, String>();
						extMap.put("image", "gif,jpg,jpeg,png,bmp,ico");
						// 获取文件名
						String fileName = file.getOriginalFilename();
						
						// 获取文件扩展名
						String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
						
						// 上传文件问图片
						if (extMap.get("image").contains(fileExt)) { // 图片
							// 上传路径
                            String path =url+"/images";
                            url = url + "images";
                            address="/upload/images";
							path = path.replaceAll("\\\\", "/");
							fileName = fileName.replaceAll("\\\\", "/");
							File filePath = new File(path, fileName);
                            System.out.println(path);
							// 判断路径是否存在，如果不存在就创建一个
							if (!filePath.getParentFile().exists()) {
								filePath.getParentFile().mkdirs();
							}
							// 文件重命名
							SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
							fileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
							
							// 将上传文件保存到目录中 + new File(path + File.separator + fileName)
							path = path.replaceAll("\\\\", "/");
							fileName = fileName.replaceAll("\\\\", "/");
							file.transferTo(new File(path + File.separator + fileName));
							 
							
							path = path + File.separator + fileName;
							url = url + File.separator + fileName + ",";
                            address=address+ File.separator + fileName+"," ;
//							System.out.println("url::"+url);
						}
					}
					url = url.replaceAll("\\\\", "/");
                    address = address.replaceAll("\\\\", "/");
                    String url0 = request.getScheme()+"://" + request.getServerName()+":" +request.getServerPort();
					saveUrl =url0+ saveUrl + address;
				if(saveUrl.length()>0)
					saveUrl = saveUrl.substring(0, saveUrl.length() - 1);
				return saveUrl;
		
	}
}
